package com.cskaoyan.config;

import com.cskaoyan.realm.MarketRealm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author stone
 * @date 2021/12/03 10:02
 */
//@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean();
        shiroFilter.setSecurityManager(securityManager);
        //使用了哪一些filter、filter作用范围、filter的顺序是什么
        //map要有序：key是url，value是filter
        LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        //filter：anon匿名、authc认证、perms权限
        filterChainDefinitionMap.put("/admin/auth/login", "anon");
        filterChainDefinitionMap.put("/admin/user/list", "authc");
        //给key对应的请求url加了一道锁 admin:list这样的锁
        filterChainDefinitionMap.put("/admin/admin/list", "perms[admin:list]");
        filterChainDefinitionMap.put("/admin/**", "authc");
        shiroFilter.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilter;
    }

    @Bean
    public DefaultWebSecurityManager securityManager(MarketRealm realm,MarketSessionManager sessionManager) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //securityManager.setAu
        //可以使用set方法设置认证器和授权器
        //也可以使用默认的认证器和授权器：ModularAuth

        //realm需要自己去提供
        // 如果没有自己提供使用的就是默认，这个默认的realm满足不了我们的需求
        //我们提供给SecurityManager，而SecurityManager提供给了默认的认证器和授权器
        securityManager.setRealm(realm);

        securityManager.setSessionManager(sessionManager);
        return securityManager;
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor advisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }
    //session管理
    //执行认证 👉 session
    //前后端分离：端口号是不同的 👉 跨域
    //把sessionId返回给前端
    //SessionManager：保证多次请求使用的是同一个session

}
